********************************************************************************
** Data construction "Mums Go Online: Is the Internet Changing the Demand 
** for Healthcare?" by Amaral-Garcia, Nardotto, Propper and Valletti.
********************************************************************************

* Part A: Prepare Hospital Discharge Data (HES)
* Part B: Internet Data and merge with HES Data 

********************************************************************************
*+++++++++++++++++++++ Part A. Prepare Hospital Discharge Data (HES)
********************************************************************************

/* Note: The Hospital Episode Statistics (HES) are copyright © 2001/02 - 2011/12, 
to the Health and Social Care Information Centre. For this paper, we re-used with 
the permission of the Health and Social Care Information Centre. In order to use 
the data, a formal request must be made.
*/

set more off, permanently

* Go to the Hospital Discharge Data on maternity, keep relevant variables and 
* clean the data

***********************************************
** Data import of discharges
***********************************************
cap cd C:\HealthInternet_UKdata\HES_OriginalData
global datapath "C:\HealthInternet_UKdata\Discharges_REStat"

set more off, permanently

forval Y=2000/2012{
	use maternity_`Y'.dta, clear

	set more off
	
	cap drop hesyear
	gen hesyear=`Y'
	
	* Keep only deliveries (mothers´ data)
	keep if epitype==2

	# delimit ;
	keep admidate admimeth admincat admisorc anagest anasdate antedur bedyear
	biresus_1-biresus_9 birstat_1 birstat_2 birweit_1-birweit_9 classpat
	delchang delinten delmeth_1-delmeth_9 delonset delplac_1 delposan delprean 
	delstat_1-delstat_3 diag_01-diag_20 diag3_01 diag4_01 disdate disdest dismeth disreadydate
	elecdate epidur epiend epiorder epistart epitype ethnos gestat_1-gestat_9 gpprac 
	hatreat hesyear hrglate35 hrgnhs hrgnhsvn
	imd04_decile imd04c imd04ed imd04em imd04hd imd04hs imd04i imd04ia imd04ic imd04le
	imd04rk mainspef matage mydob neocare neodur numbaby numpreg
	oacode6 opertn_01-opertn_24 opertn3_01 pconsult pctcode pctcode06
	pctnhs postdist postdur procode procode3 protype provspno 
	rescty resladst respct respct06 resro resstha resstha06 rotreat rururb_ind
	sex sexbaby_1-sexbaby_9 sitetret soal soam speldur spelend tretspef ward91 wardstrt
	well_baby_ind ;	
	#delimit cr
	
	* Dates
	cap la var admidate "Admission date"

	gen year_adm=substr(admidate, 1,4)
	destring year_adm, replace

	gen month_adm=substr(admidate, 6,2)
	destring month_adm, replace

	cap la var hesyear "HES Year"
	
	cap la var disdate "Date of discharge"
	cap la var epiend "Date episode ended"
	cap la var epistart "Date episode started"
	cap la var elecdate "Date of decision to admit"
	cap la var speldur "Duration of spell"
	cap la var spelend "End of spell"
	cap la var epidur "Episode duration"	
	cap la var disreadydate "Discharge ready date" // Not necessarily the same as disdate
	**format dates
	foreach var in elecdate admidate disdate epistart epiend {
		tostring `var', replace
		replace `var'= "0"+`var' if length(`var')<8 & `var'!=""
		gen date = date(`var',"YMD")
		drop `var'
		ren date `var'
		format %td `var'
	}
	
	* Patients´characteristics
	cap la var admincat "Adm cat - 1 for NHS" // Vast majority are admincat==1
	cap la var neodur "Age of baby in days"
	cap la var mydob "Date of birth" // Month and year
	cap la var ethnos "Ethnicity"
	*cap destring hesid, replace 
	cap la var postdist "Postcode district of patient's residence"
	cap la var sex "Patient´s gender"
	cap label define sex 1 "Male" 2 "Female"

	gen female=(sex==2)
	cap la var female "Female Patient"

	cap la var soal "LSOA"
	cap la var classpat "Patient classification"
	
	* Method of admission/discharge
	cap la var admimeth "Method of admission" 
	cap drop admimeth_new
	cap drop admimeth_recode
	
	gen admimeth_new=admimeth
	destring admimeth_new, replace
	
	recode admimeth_new (31=1 "ante-partum") (32=2 "post-partum") ///
	(82=3 "birth") (83=4 "baby born out"), generate(admimeth_recode)
	
	cap la var admimeth_recode "method of admission"
	cap la var admisorc "Source of admission"
	cap la var dismeth "Method of discharge"
	cap la var bedyear "Bed days within the year"
	cap la var epitype "Episode type" 
	label define epitype_lbl 1 "general" 2 "delivery" 3 "birth" 4 "mental health" 5 "other delivery" 6 "other birth event", replace
	label values epitype epitype_lbl

	cap la var disdest "Destination on discharge" 
	cap la var provspno "SENSI-Hospital provider spell number"
	cap la var wardstrt "Ward type at start of episode" 
	cap la var mainspef "Main specialty"
	cap la var tretspef "Treatment specialty"
	cap la var sitetret ""
	cap la var procode "Trust code"
	cap la var procode3 "Provider code"
	cap la var protype "Provider Type"
	cap la var pconsult "pseudonymised consultant team code"
	
	cap la var diag_01 "Primary diagnosis"
	cap la var opertn_01 "Primary procedure"

	forvalues i=1/9 {
		tostring diag_0`i', replace
	}
	
	forvalues i=10/20 {
		tostring diag_`i', replace
	}
	
	cap la var diag_01 "Primary diagnosis"
	cap la var diag_02 "Diagnosis 2"

	forvalues i=1/9 {
		cap rename diag_0`i' diag_`i'
		cap rename opertn_0`i' opertn_`i'
	}

	forvalues i=1/24 { 		
	tostring opertn_`i', replace		
	}

	cap la var pctcode06 "Primary care trust of responsibility - current"
	cap la var pctcode "Primary care trust of responsibility"
	cap la var oacode6 "Census Output Area, 2006"
	cap la var oacode1 "Census Output Area, 2001"
	cap la var rescty "County of residence"
	cap la var resladst "Local authority district"
	cap la var ward91 "Electoral ward in 1991"
	cap la var hatreat "Health Authority of treatment"
	cap la var pctnhs ""
	cap la var respct06 "Patient's Primary Care Trust of residence - current"
	cap la var respct "Patient's Primary Care Trust of residence"
	cap la var resstha "Patient's Strategic Health Authority of residence"
	cap la var resstha06 "Patient's Strategic Health Authority of residence-current"
	cap la var rotreat "Region of treatment"
	cap la var resro "Regional Office of residence" 
	cap la var rururb_ind "Rural/Urban Indicator"

	cap la var gpprac "Code of GP practice"

	cap la var delprean "Anaesthetic given during labour or delivery"
	cap la var delposan "Anaesthetic given post-labour or delivery"
	cap la var antedur "Antenatal days of stay"

	forvalues val=1/9 {
		cap la var birweit_`val' "Birth weight"
		}
	forvalues val=1/9 {
		cap la var delmeth_`val' "Alternative Delivery method"
		}
		
	cap la var delplac_1 "Delivery place - actual"
	cap la var delinten "Delivery place-intended"
	cap la var delchang "Delivery place change reason"
	cap la var anasdate "First antenatal assessment date"
	cap la var anagest "Gestation period in weeks at first antenatal assessment"
	cap la var birstat_1 "Birth status"
	cap la var birstat_2 "Birth status 2"
	cap la var delonset "Labour/delivery onset method"
	cap la var matage "Mother's age at delivery"
	cap la var numbaby "Number of babies"
	cap la var numpreg "Number of previous pregnancies"
	cap la var postdur "Postnatal stay"
	cap la var neocare "Neonatal level of care"	
	cap la var well_baby_ind "Well baby flag"
	cap la var maternity "Maternity - TO CHECK"
	cap la var babies "Babies - TO CHECK"
	
	forvalues val=1/9 {
		cap la var biresus_`val' "Resuscitation method"
		}
	forvalues val=1/9 {
		cap la var sexbaby_`val' "Baby sex"
		}
	forvalues val=1/3 {
		cap la var delstat_`val' "Status of person conducting delivery"
		}
		
	cap la var gestat_1 "Length gestation"

	* Indices of multiple deprivation
	encode imd04_decile, generate(imd04_decile_new)
	cap la var imd04_decile_new "imd decile group"
	cap la var imd04c  "imd crime domain"
	cap la var imd04ed "imd education training and skills domain"
	cap la var imd04em "imd employment deprivation domain"
	cap la var imd04hd "imd health and disability domain"
	cap la var imd04hs "imd barriers to housing and service domain"
	cap la var imd04i  "imd income domain"
	cap la var imd04ia "imd income affecting adults domain"
	cap la var imd04ic "imd income affecting children domain"
	cap la var imd04le "imd living environment domain"
	cap la var imd04rk "imd overall rank"
	cap la var imd04   "imd indice of multiple deprivation"
	
compress

	***********************************
	* Flag types of delivery methods
	***********************************
	forvalues i=1/24 {
		replace opertn_`i'=subinstr(opertn_`i', "-", "", .)
	}

	forvalues i=1/20 {
		replace diag_`i'=subinstr(diag_`i', "-", "", .)
	}

	* 1-Elective C-section
	gen del_csecelect = 0 
	foreach lname in R171 R172 R178 R179 {
	replace del_csecelect = 1 if (opertn_1 == "`lname'" | opertn_2 == "`lname'" |opertn_3 == "`lname'" | opertn_4 == "`lname'" | opertn_5 == "`lname'")
	replace del_csecelect = 1 if (opertn_6 == "`lname'" | opertn_7 == "`lname'" |opertn_8 == "`lname'" | opertn_9 == "`lname'" | opertn_10 == "`lname'")
	replace del_csecelect = 1 if (opertn_11 == "`lname'" | opertn_12 == "`lname'" |opertn_13 == "`lname'" | opertn_14 == "`lname'" | opertn_15 == "`lname'")
	replace del_csecelect = 1 if (opertn_16 == "`lname'" | opertn_17 == "`lname'" |opertn_18 == "`lname'" | opertn_19 == "`lname'" | opertn_20 == "`lname'")
	replace del_csecelect = 1 if (opertn_21 == "`lname'" | opertn_22 == "`lname'" |opertn_23 == "`lname'" | opertn_24 == "`lname'")
	}
	la var del_csecelect "Del-Elective C-sec"

	* 2- Emergency C-section
	gen del_csecemerg = 0 
	foreach lname in R181 R182 R188 R189 {
	replace del_csecemerg = 1 if (opertn_1 == "`lname'" | opertn_2 == "`lname'" |opertn_3 == "`lname'" | opertn_4 == "`lname'" | opertn_5 == "`lname'")
	replace del_csecemerg = 1 if (opertn_6 == "`lname'" | opertn_7 == "`lname'" |opertn_8 == "`lname'" | opertn_9 == "`lname'" | opertn_10 == "`lname'")
	replace del_csecemerg = 1 if (opertn_11 == "`lname'" | opertn_12 == "`lname'" |opertn_13 == "`lname'" | opertn_14 == "`lname'" | opertn_15 == "`lname'")
	replace del_csecemerg = 1 if (opertn_16 == "`lname'" | opertn_17 == "`lname'" |opertn_18 == "`lname'" | opertn_19 == "`lname'" | opertn_20 == "`lname'")
	replace del_csecemerg = 1 if (opertn_21 == "`lname'" | opertn_22 == "`lname'" |opertn_23 == "`lname'" | opertn_24 == "`lname'")
	}
	la var del_csecemerg "Del-Emergency C-sec"

	* 3- Breech Extraction
	gen del_breechext = 0 
	foreach lname in R191 R198 R199 {
	replace del_breechext = 1 if (opertn_1 == "`lname'" | opertn_2 == "`lname'" |opertn_3 == "`lname'" | opertn_4 == "`lname'" | opertn_5 == "`lname'")
	replace del_breechext = 1 if (opertn_6 == "`lname'" | opertn_7 == "`lname'" |opertn_8 == "`lname'" | opertn_9 == "`lname'" | opertn_10 == "`lname'")
	replace del_breechext = 1 if (opertn_11 == "`lname'" | opertn_12 == "`lname'" |opertn_13 == "`lname'" | opertn_14 == "`lname'" | opertn_15 == "`lname'")
	replace del_breechext = 1 if (opertn_16 == "`lname'" | opertn_17 == "`lname'" |opertn_18 == "`lname'" | opertn_19 == "`lname'" | opertn_20 == "`lname'")
	}
	la var del_breechext "Del-Breech Extraction"

	* 4- Breech - Other
	gen del_breech=0
	foreach lname in R201 R202 R208 R209 {
	replace del_breech = 1 if (opertn_1 == "`lname'" | opertn_2 == "`lname'" |opertn_3 == "`lname'" | opertn_4 == "`lname'" | opertn_5 == "`lname'")
	replace del_breech = 1 if (opertn_6 == "`lname'" | opertn_7 == "`lname'" |opertn_8 == "`lname'" | opertn_9 == "`lname'" | opertn_10 == "`lname'")
	replace del_breech = 1 if (opertn_11 == "`lname'" | opertn_12 == "`lname'" |opertn_13 == "`lname'" | opertn_14 == "`lname'" | opertn_15 == "`lname'")
	replace del_breech = 1 if (opertn_16 == "`lname'" | opertn_17 == "`lname'" |opertn_18 == "`lname'" | opertn_19 == "`lname'" | opertn_20 == "`lname'")
	}
	la var del_breech "Del-Breech other"

	* 5 - Forceps-Other
	gen del_forceps=0
	foreach lname in R211 R212 R213 R214 R218 R219 {
	replace del_forceps = 1 if (opertn_1 == "`lname'" | opertn_2 == "`lname'" |opertn_3 == "`lname'" | opertn_4 == "`lname'" | opertn_5 == "`lname'")
	replace del_forceps = 1 if (opertn_6 == "`lname'" | opertn_7 == "`lname'" |opertn_8 == "`lname'" | opertn_9 == "`lname'" | opertn_10 == "`lname'")
	replace del_forceps = 1 if (opertn_11 == "`lname'" | opertn_12 == "`lname'" |opertn_13 == "`lname'" | opertn_14 == "`lname'" | opertn_15 == "`lname'")
	replace del_forceps = 1 if (opertn_16 == "`lname'" | opertn_17 == "`lname'" |opertn_18 == "`lname'" | opertn_19 == "`lname'" | opertn_20 == "`lname'")
	}
	la var del_forceps "Del-Forceps"

	* 6- Forceps-Low
	gen del_forcepslow=0
	foreach lname in R215 {
	replace del_forcepslow = 1 if (opertn_1 == "`lname'" | opertn_2 == "`lname'" |opertn_3 == "`lname'" | opertn_4 == "`lname'" | opertn_5 == "`lname'")
	replace del_forcepslow = 1 if (opertn_6 == "`lname'" | opertn_7 == "`lname'" |opertn_8 == "`lname'" | opertn_9 == "`lname'" | opertn_10 == "`lname'")
	replace del_forcepslow = 1 if (opertn_11 == "`lname'" | opertn_12 == "`lname'" |opertn_13 == "`lname'" | opertn_14 == "`lname'" | opertn_15 == "`lname'")
	replace del_forcepslow = 1 if (opertn_16 == "`lname'" | opertn_17 == "`lname'" |opertn_18 == "`lname'" | opertn_19 == "`lname'" | opertn_20 == "`lname'")
	}
	la var del_forcepslow "Del-Forceps"

	* 7 - Ventouse
	gen del_vent=0
	foreach lname in R221 R222 R223 R228 R229 {
	replace del_vent = 1 if (opertn_1 == "`lname'" | opertn_2 == "`lname'" |opertn_3 == "`lname'" | opertn_4 == "`lname'" | opertn_5 == "`lname'")
	replace del_vent = 1 if (opertn_6 == "`lname'" | opertn_7 == "`lname'" |opertn_8 == "`lname'" | opertn_9 == "`lname'" | opertn_10 == "`lname'")
	replace del_vent = 1 if (opertn_11 == "`lname'" | opertn_12 == "`lname'" |opertn_13 == "`lname'" | opertn_14 == "`lname'" | opertn_15 == "`lname'")
	replace del_vent = 1 if (opertn_16 == "`lname'" | opertn_17 == "`lname'" |opertn_18 == "`lname'" | opertn_19 == "`lname'" | opertn_20 == "`lname'")
	}
	la var del_vent "Del-Ventouse"

	* 8- Spontaneous - Other
	gen del_spont=0
	foreach lname in R231 R232 R238 R239 {
	replace del_spont = 1 if (opertn_1 == "`lname'" | opertn_2 == "`lname'" |opertn_3 == "`lname'" | opertn_4 == "`lname'" | opertn_5 == "`lname'")
	replace del_spont = 1 if (opertn_6 == "`lname'" | opertn_7 == "`lname'" |opertn_8 == "`lname'" | opertn_9 == "`lname'" | opertn_10 == "`lname'")
	replace del_spont = 1 if (opertn_11 == "`lname'" | opertn_12 == "`lname'" |opertn_13 == "`lname'" | opertn_14 == "`lname'" | opertn_15 == "`lname'")
	replace del_spont = 1 if (opertn_16 == "`lname'" | opertn_17 == "`lname'" |opertn_18 == "`lname'" | opertn_19 == "`lname'" | opertn_20 == "`lname'")
	}
	la var del_spont "Del-Spontaneous other"

	* 9- Spontaneous - Vertex - this should be what is commonly called a "normal" delivery
	gen del_normal=0
	foreach lname in R249 {
	replace del_normal = 1 if (opertn_1 == "`lname'" | opertn_2 == "`lname'" |opertn_3 == "`lname'" | opertn_4 == "`lname'" | opertn_5 == "`lname'")
	replace del_normal = 1 if (opertn_6 == "`lname'" | opertn_7 == "`lname'" |opertn_8 == "`lname'" | opertn_9 == "`lname'" | opertn_10 == "`lname'")
	replace del_normal = 1 if (opertn_11 == "`lname'" | opertn_12 == "`lname'" |opertn_13 == "`lname'" | opertn_14 == "`lname'" | opertn_15 == "`lname'")
	replace del_normal = 1 if (opertn_16 == "`lname'" | opertn_17 == "`lname'" |opertn_18 == "`lname'" | opertn_19 == "`lname'" | opertn_20 == "`lname'")
	}
	la var del_normal "Del-Normal Spontaneous Vertex"

	* 10- Other
	gen del_other=0
	foreach lname in R251 R252 R258 R259 {
	replace del_other = 1 if (opertn_1 == "`lname'" | opertn_2 == "`lname'" |opertn_3 == "`lname'" | opertn_4 == "`lname'" | opertn_5 == "`lname'")
	replace del_other = 1 if (opertn_6 == "`lname'" | opertn_7 == "`lname'" |opertn_8 == "`lname'" | opertn_9 == "`lname'" | opertn_10 == "`lname'")
	replace del_other = 1 if (opertn_11 == "`lname'" | opertn_12 == "`lname'" |opertn_13 == "`lname'" | opertn_14 == "`lname'" | opertn_15 == "`lname'")
	replace del_other = 1 if (opertn_16 == "`lname'" | opertn_17 == "`lname'" |opertn_18 == "`lname'" | opertn_19 == "`lname'" | opertn_20 == "`lname'")
	}
	la var del_other "Del-Other"

	* 11-Unknown
	gen del_unk=0
	replace del_unk=1 if epitype==2 & (del_csecelect==0 & del_csecemerg==0 & del_breechext==0 & del_breech==0 & del_forceps==0 & del_forcepslow==0 & del_vent==0 & del_spont==0 & del_normal==0 & del_other==0 & del_vent==0 & del_unk==0)
	la var del_unk "Del-Unkown"

	* Delivery method-General variable
	gen del=1 if del_csecelect==1
	replace del=2 if del_csecemerg==1
	replace del=3 if del_breechext==1
	replace del=4 if del_breech==1
	replace del=5 if del_forceps==1
	replace del=6 if del_forcepslow==1
	replace del=7 if del_vent==1
	replace del=8 if del_spont==1
	replace del=9 if del_normal==1
	replace del=10 if del_other==1
	replace del=11 if del_unk==1

	recode del (1=1 "Csec elective") (2=2 "Csec emerg") (3=3 "Breech Extract")  ///
	(4=4 "Breech") (5=5 "Forceps") (6=6 "Forceps Low") (7=7 "Ventouse")  ///
	(8=8 "Spontaneous oth") (9=9 "Spontaneous Vertex") (10=10 "Other") ///
	(11=11 "Unkown"), gen(del_method)
	cap la var del_method "Delivery method-mothers"

	gen csec=(del==1 | del==2)
	la var csec "C-section"

	* Previous CS
	gen previousCS = 0
	foreach lname in O757 O342 { 
			replace previousCS = 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace previousCS = 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	la var previousCS "Previous C-section"

	*****************************************************	
	*  Age of mothers
	*****************************************************
	tostring mydob, replace
	gen temp1=length(mydob)
	replace temp1=temp1-3
	gen patyob=substr(mydob,temp1,.)
	destring patyob, replace
	drop temp1 mydob
	la var patyob "Mother's yob"
	
	gen patage=year_adm-patyob
	la var patage "Age"
	
	* make age groups
	gen agegroup = .
	replace agegroup = 1 if patage < 20
	replace agegroup = 2 if patage >= 20 & patage <= 24
	replace agegroup = 3 if patage >= 25 & patage <= 29 
	replace agegroup = 4 if patage >= 30 & patage <= 34
	replace agegroup = 5 if patage >= 35 & patage <= 39
	replace agegroup = 6 if patage >= 40
	tab agegroup, gen(agedum)	
	
	*****************************************************	
	* Anemia 
	*****************************************************
	gen anemia=0
	foreach lname in O990 D50 D500 D501 D508 D509 D51 D510 D511 D512 D513 D518 D519 D52 D520 D521 D528 D529 D53 D530 D531 D532 D538 D539 D55 D550 D551 D552 D553 D558 D55 D56 D560 D561 D562 D563 D564 D565 D568 D569 {
			replace anemia=1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace anemia=1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	foreach lname in D57 D570 D571 D572 D573 D574 D578 D58 D580 D581 D582 D588 D589 D59 D590 D591 D592 D593 D594 D595 D596 D598 D599 D60 D600 D601 D608 D609 D61 D610 D611 D612 D613 D618 D619 D62 D63 D630 D638 D64 D640 D641 D642 D643 D644 D648 D649 {
			replace anemia=1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace anemia=1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	la var anemia "Anemia"
	
	*****************************************************	
	* Breech 
	*****************************************************
	gen breech=0
	foreach lname in O321 O641 O322 O323 O801 O830 O831 { 
			replace breech=1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace breech=1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	foreach lname in R19 R191 R198 R199 R20 R201 R202 R208 R209 {
		replace breech=1 if (opertn_1 == "`lname'" | opertn_2 == "`lname'" |opertn_3 == "`lname'" | opertn_4 == "`lname'" | opertn_5 == "`lname'")
		replace breech=1 if (opertn_6 == "`lname'" | opertn_7 == "`lname'" |opertn_8 == "`lname'" | opertn_9 == "`lname'" | opertn_10 == "`lname'")
		replace breech=1 if (opertn_11 == "`lname'" | opertn_12 == "`lname'" |opertn_13 == "`lname'" | opertn_14 == "`lname'" | opertn_15 == "`lname'")
		replace breech=1 if (opertn_16 == "`lname'" | opertn_17 == "`lname'" |opertn_18 == "`lname'" | opertn_19 == "`lname'" | opertn_20 == "`lname'")
	}
	la var breech "Breech position"

	*****************************************************							
	* Cardiac & Lung Conditions
	*****************************************************							
	gen cardiaclung=0									
	foreach lname in I43 I430 I431 I432 I438 I44 I440 I441 I442 I443 I444 I445 I446 I447 I45 I450 I451 I452 I453 I454 I455 I456 I458 I459 I46 I460 I461 I469 {
			replace cardiaclung=1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace cardiaclung=1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	foreach lname in I47 I470 I471 I479 I48 I49 I490 I491 I492 I493 I494 I495 I498 I499 I50 I500 I501 I509 I51 I510 I511 I512 I513 I514 I515 I516 I517 I518 I519 {
			replace cardiaclung=1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace cardiaclung=1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	foreach lname in I52 I520 I521 I528 I971 O088 Q21 Q210 Q211 Q212 Q213 Q214 Q218 Q219 Q22 Q220 Q221 Q222 Q223 Q224 Q225 Q226 Q228 Q229   {
			replace cardiaclung=1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace cardiaclung=1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	foreach lname in Q23 Q230 Q231 Q232 Q233 Q234 Q238 Q239 Q24 Q240 Q241 Q242 Q243 Q244 Q245 Q246 Q248 Q249 Q25 Q250 Q251 Q252 Q253 Q254 Q255 Q256 Q257 Q258 Q259 {
			replace cardiaclung=1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace cardiaclung=1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	foreach lname in Q26 Q260 Q261 Q262 Q263 Q264 Q265 Q266 Q268 Q269 R01 R010 R011 R012 R943 T82 T820 T821 T822 T823 T824 T825 T826 T827 T828 Y520 Y840 Z450 Z500{ 
			replace cardiaclung=1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace cardiaclung=1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	foreach lname in Z950 Z951 Z952 Z953 Z954 Z955 Z958 Z959 P290 P291 {
			replace cardiaclung=1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace cardiaclung=1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	foreach lname in A065 A150 A151 A152 A153 A154 A155 A156 A157 A158 A159 A16 A160 A161 A162 A163 A164 A165 A167 A168 A169 {
			replace cardiaclung=1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace cardiaclung=1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	foreach lname in B671 C34 C340 C341 C342 C344 C349 C38 C380 C381 C382 C383 C384 C388 C780 D022 D143 D860 D862 {
			replace cardiaclung=1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace cardiaclung=1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	foreach lname in J60 J61 J62 J620 J628 J63 J630 J631 J632 J633 J634 J635 J638 J64 J65 J66 J660 J661 J662 J668 {
			replace cardiaclung=1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace cardiaclung=1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	foreach lname in J67 J670 J671 J672 J673 J674 J675 J676 J677 J678 J679 J68 J680 J681 J682 J683 J684 J688 J689 J69 J690 J691 J698 {
			replace cardiaclung=1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace cardiaclung=1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	foreach lname in J70 J700 J701 J702 J703 J704 J708 J709 J80 J81 J82 J84 J840 J841 J848 J849 J85 J850 J851 J852 J853 J86 J860 J869 {
			replace cardiaclung=1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace cardiaclung=1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	foreach lname in J90 J91 J92 J920 J929 J93 J930 J931 J938 J939 J94 J940 J941 J942 J948 J949 J95 J950 J951 J952 J953 J954 J955 J958 J959 { 
			replace cardiaclung=1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace cardiaclung=1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	foreach lname in J96 J960 J961 J969 J98 J980 J981 J982 J983 J984 J985 J986 J988 J989 J99 J990 J991 J998 {
			replace cardiaclung=1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace cardiaclung=1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	la var cardiaclung "Cardiac and lung conditions"

	*****************************************************
	* Cervix		
	*****************************************************								
	gen cervix=0	
	foreach lname in O343 O344 C53 C530 C531 C538 C539 D06 D060 D061 D067 D069 N72 A181 N841 N86 N87 N879 N88 N880 N881 N882 N883 N884 N888 N889 Q511 Q515 Q516 Q518 Q519 {
		replace cervix=1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
		replace cervix=1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	la var cervix "Incompetent Cervix and other cervix anomalies"
	
	*****************************************************	
	*  Comorbidities
	*****************************************************
	gen morb=0
	foreach lname in  O730 O740 O742 O744 O746 O751 O860 O862 O864 O871 O881 O894 O900 O902 O904 R060 R074 T810 {
			replace morb = 100 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace morb = 100 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	foreach lname in  O710 O721 O723 O741 O743 O745 O747 O85 O861 O863 O868 O880 O882 O895 O901 {
 			replace morb = 100 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace morb = 100 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}	
	la var morb "Co-morbidities"
	
	***********************************************************
	* Cord prolapse 
	**********************************************************		
	gen cordprol=0									
	foreach lname in O690 {
		replace cordprol= 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
		replace cordprol= 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	la var cordprol "Cord Prolapse"

	************************************************************************************************																
	* Disproportion
	************************************************************************************************									
	gen disprop=0									
	foreach lname in O654 O330 O331 O332 O333 O334 O335 O336 O337 O338 O339 P031 {
		replace disprop= 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
		replace disprop= 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	la var disprop "Disproportion-includes cephalo"	
	
	*****************************************************	
	* Diabetes 
	*****************************************************
	gen diabetes = 0
	foreach lname in O240 O241 O242 O243 O244 O249 E10 E100 E101 E102 E103 E104 E105 E106 E107 E108 E109 E11 E110 E111 E112 E113 E114 E115 E116 E117 E118 E119 {
			replace diabetes = 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace diabetes = 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	foreach lname in E12 E120 E121 E122 E123 E124 E125 E126 E127 E128 E129 E13 E130 E131 E132 E133 E134 E135 E136 E137 E138 E139 E14 E140 E141 E142 E143 E144 E145 E146 E147 E148 E149 {
			replace diabetes = 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace diabetes = 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	foreach lname in E15 E150 E151 E152 E153 E154 E155 E156 E157 E158 E159 E16 E160 E161 E162 E163 E164 E168 E169 R73 R730 R739 {
			replace diabetes = 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace diabetes = 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	la var diabetes "Diabetes"	
	
	*****************************************************	
	*  Episiotomy
	*****************************************************
	gen epis=0
	foreach lname in R271 P141 P142 P143 {
		replace epis=1 if (opertn_1 == "`lname'" | opertn_2 == "`lname'" |opertn_3 == "`lname'" | opertn_4 == "`lname'" | opertn_5 == "`lname'")
		replace epis=1 if (opertn_6 == "`lname'" | opertn_7 == "`lname'" |opertn_8 == "`lname'" | opertn_9 == "`lname'" | opertn_10 == "`lname'")
		replace epis=1 if (opertn_11 == "`lname'" | opertn_12 == "`lname'" |opertn_13 == "`lname'" | opertn_14 == "`lname'" | opertn_15 == "`lname'")
		replace epis=1 if (opertn_16 == "`lname'" | opertn_17 == "`lname'" |opertn_18 == "`lname'" | opertn_19 == "`lname'" | opertn_20 == "`lname'")
	}
	la var epis "Episiotomy"

	*****************************************************	
	* Fetal Distress 
	*****************************************************
	gen distress = 0
	foreach lname in O68 O680 O681 O682 O683 O688 O689 P20 P200 P201 P209 { 
			replace distress = 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace distress = 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	la var distress "Fetal distress"
	
	*****************************************************				
	* Herpes	
	*****************************************************										
	gen herpes=0
	foreach lname in A60 A600 A601 A609 B00 B001 B002 B003 B004 B005 B007 B008 B009 B02 B020 B021 B022 B023 B027 B028 B029 B270{
		replace herpes = 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
		replace herpes = 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	la var herpes "Herpes"
	
	*****************************************************	
	*  Hypertension+eclampsia
	*****************************************************
	gen hypereclamp = 0
	foreach lname in O10 O100 O101 O102 O103 O104 O109 O11 O111 O112 O113 O13 O131 O132 O133 O139 O14 O140 O141 O149 O15 O150 O151 O152 O159 O16 O161 O162 O163 {
			replace hypereclamp = 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace hypereclamp = 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	la var hypereclamp "Hypertension + eclampsia"
	
	*****************************************************											
	* Induction of labor
	*****************************************************
	gen induction=0
	foreach lname in R14 R141 R142 R148 R149 R15 R151 R158 R159 {
		replace induction = 1 if (opertn_1 == "`lname'" | opertn_2 == "`lname'" |opertn_3 == "`lname'" | opertn_4 == "`lname'" | opertn_5 == "`lname'")
		replace induction = 1 if (opertn_6 == "`lname'" | opertn_7 == "`lname'" |opertn_8 == "`lname'" | opertn_9 == "`lname'" | opertn_10 == "`lname'")
		replace induction = 1 if (opertn_11 == "`lname'" | opertn_12 == "`lname'" |opertn_13 == "`lname'" | opertn_14 == "`lname'" | opertn_15 == "`lname'")
		replace induction = 1 if (opertn_16 == "`lname'" | opertn_17 == "`lname'" |opertn_18 == "`lname'" | opertn_19 == "`lname'" | opertn_20 == "`lname'")
		replace induction = 1 if (opertn_21 == "`lname'" | opertn_22 == "`lname'" |opertn_23 == "`lname'" | opertn_24 == "`lname'")
		}
	la var induction "Labor induction"	

	*****************************************************																																																																	
	* Obesity
	*****************************************************											
	gen obesity=0									
	foreach lname in E65 E66 E660 E661 E662 E668 E669  {
		replace obesity= 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
		replace obesity= 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	la var obesity "Obesity"
	
	*********************************************
	* Obstetric Trauma
	*********************************************

	**** PSI 18: Obstetric Trauma - Vaginal Delivery with Instrument
	gen trvaginstr=0 
	foreach lname in O70 O700 O701 O702 O703 O709 O713 O714 O715 O716 {
			replace trvaginstr = 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace trvaginstr = 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	foreach lname in R321 R322 R323 R324 R328 R329 {
	replace trvaginstr= 1 if (opertn_1 == "`lname'" | opertn_2 == "`lname'" |opertn_3 == "`lname'" | opertn_4 == "`lname'" | opertn_5 == "`lname'")
		replace trvaginstr= 1 if (opertn_6 == "`lname'" | opertn_7 == "`lname'" |opertn_8 == "`lname'" | opertn_9 == "`lname'" | opertn_10 == "`lname'")
		replace trvaginstr= 1 if (opertn_11 == "`lname'" | opertn_12 == "`lname'" |opertn_13 == "`lname'" | opertn_14 == "`lname'" | opertn_15 == "`lname'")
		replace trvaginstr= 1 if (opertn_16 == "`lname'" | opertn_17 == "`lname'" |opertn_18 == "`lname'" | opertn_19 == "`lname'" | opertn_20 == "`lname'")
	}
	la var trvaginstr "Trauma vag del with instrument"		

	**** PSI 19: Obstetric Trauma - Vaginal Delivery without Instrument
	gen trvagnoinstr=0 
	foreach lname in O70 O700 O701 O702 O703 O709 O713 O714 O715 O716 {
			replace trvagnoinstr = 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace trvagnoinstr = 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	 foreach lname in R321 R322 R323 R324 R328 R329 {
		replace trvagnoinstr=1 if (opertn_1 == "`lname'" | opertn_2 == "`lname'" |opertn_3 == "`lname'" | opertn_4 == "`lname'" | opertn_5 == "`lname'")
		replace trvagnoinstr=1 if (opertn_6 == "`lname'" | opertn_7 == "`lname'" |opertn_8 == "`lname'" | opertn_9 == "`lname'" | opertn_10 == "`lname'")
		replace trvagnoinstr=1 if (opertn_11 == "`lname'" | opertn_12 == "`lname'" |opertn_13 == "`lname'" | opertn_14 == "`lname'" | opertn_15 == "`lname'")
		replace trvagnoinstr=1 if (opertn_16 == "`lname'" | opertn_17 == "`lname'" |opertn_18 == "`lname'" | opertn_19 == "`lname'" | opertn_20 == "`lname'")
	}
	la var trvagnoinstr "Trauma vag del without instrument"
	
	*****************************************************	
	*  Placenta Previa
	*****************************************************
	gen placprevia = 0
	foreach lname in O44 O440 O441 {
			replace placprevia = 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace placprevia = 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	la var placprevia "Placenta previa"

	*****************************************************	
	*  Premature Rupture of Membranes
	*****************************************************
	gen prematmem = 0
	foreach lname in O42 O420 O421 O422 O429 {
			replace prematmem = 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace prematmem = 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	la var prematmem "Premature rupture of the membranes"

	*****************************************************
	* Previous abortion
	*****************************************************
	gen prevabortion=0	
	foreach lname in O262 O311 {
		replace prevabortion= 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
		replace prevabortion= 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	la var prevabortion "Previous abortion"
	
	*****************************************************
	* Prolonged labor
	*****************************************************													
	gen prolonglab=0
	foreach lname in O63 O630 O631 O632 O639 {
		replace prolonglab= 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
		replace prolonglab= 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}							
	la var prolonglab "Prolonged labor"

	*****************************************************				
	* Prolonged pregnancy
	***************************************************** 										
	gen prolongpg=0			 		
	foreach lname in O48 {
		replace prolongpg= 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
		replace prolongpg= 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	la var prolongpg "Prolonged Pregnancy"

	*****************************************************
	* Renal Failure 
	*****************************************************
	gen renal = 0
	foreach lname in N17 N170 N171 N172 N178 N179 N18 N180 N188 N189 N19 P960 O084 {
		replace renal= 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
		replace renal= 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	foreach lname in I120 I129 I13 I130 I131 I132 I139 I151 {
		replace renal= 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
		replace renal= 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	foreach lname in O102 O103 O268 {
		replace renal= 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
		replace renal= 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	la var renal "Renal Failure"

	*****************************************************										
	* Rh Sensitivity		
	*****************************************************									
	gen rh=0							
	foreach lname in O360 R376 P550 {
		replace rh= 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
		replace rh= 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	la var rh "Rh sensivity"
	
	*****************************************************	
	*  Vaginal birth after C-sec
	*****************************************************
	gen vbac=0
	foreach lname in O757 {
			replace vbac = 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace vbac = 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}
	la var vbac "Vaginal birth after c-section"
	
	
	*****************************************************	
	*  Twins / multiple pregnancy
	*****************************************************
	g twins=0
	foreach lname in O30 O300 O301 O302 O308 O309 O31 O310 O311 O312 O318 O325 O337 O632 O661 Z372 Z373 Z374 Z375 Z376 Z377 Z383 Z384 Z385 Z386 Z387 Z388 O84 O840 O841 O842 O848 O849 P015{
			replace twins = 1 if (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
			replace twins = 1 if (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
	}	
	foreach lname in R072 R078 R079 R082 R088 R089 {
		replace twins=1 if (opertn_1 == "`lname'" | opertn_2 == "`lname'" |opertn_3 == "`lname'" | opertn_4 == "`lname'" | opertn_5 == "`lname'")
		replace twins=1 if (opertn_6 == "`lname'" | opertn_7 == "`lname'" |opertn_8 == "`lname'" | opertn_9 == "`lname'" | opertn_10 == "`lname'")
		replace twins=1 if (opertn_11 == "`lname'" | opertn_12 == "`lname'" |opertn_13 == "`lname'" | opertn_14 == "`lname'" | opertn_15 == "`lname'")
		replace twins=1 if (opertn_16 == "`lname'" | opertn_17 == "`lname'" |opertn_18 == "`lname'" | opertn_19 == "`lname'" | opertn_20 == "`lname'")
	}	
	la var twins "Multiple pregnancy"	
	
	
	compress
	save $datapath\DatasetDeliveries_`Y'.dta, replace
}


********************************************************************************
*+++++++++++++++++++++ Part B. Internet Data and merge with HES Data
********************************************************************************

*****************************************************************
* PART 1. Geospatial data

* 1. Import of the map in Stata
#delimit ;
shp2dta using Gis\LSOA\LSOA_2011_WGS84, 
database(Gis\LSOA\LSOA_2011_WGS84) 
coordinates(Gis\LSOA\LSOA_2011_WGS84XY) 
genid(id) gencentroids(lsoa) replace;
#delimit cr
* Geo map for merge with data
rename LSOA11CD lsoa_code
drop LSOA11NM LSOA11NMW
save Gis\LSOA\LSOA_2011_WGS84ForMerge.dta, replace

* 2. Contiguity matrix
use Gis\LSOA\LSOA_2011_WGS84, clear
spmat contiguity contiglsoas using Gis\LSOA\LSOA_2011_WGS84XY.dta , id(id) normalize(minmax) saving(Gis\LSOA\LSOAsContigList, replace) replace
insheet using Gis\LSOA\LSOAsContigList.txt, delimiter(" ") clear
rename v1 id
drop if _n==1
save Gis\LSOA\LSOAsContigListWide.dta, replace
save Gis\LSOA\LSOAsContigListWide.dta, v(11) replace
* Merge the long version with distances
reshape long v, i(id) j(neigh)
drop neigh
rename v id2
drop if id2==.
sort id id2
save Gis\LSOA\LSOAsContigListLong.dta, replace

* 3. Coordinates LEs
use Gis\LEs\DPaddressBookEng2WGS84.dta, clear
keep code le_x le_y
rename code le_code
save Gis\LEs\DPaddressBookEng2WGS84ForMerge.dta, replace

* Mata routine for distance - 2 columns solution
use Gis\LSOA\LSOAsContigList.dta, clear
mata
contmatwide=st_data(.,.,)
nid=rows(contmatwide)
lastcol=cols(contmatwide)
newmat=J(50000000,3,.)
gcount=0
//end
for(i=1;i<=nid;i++) {
//mata
//i=1
	lev1vec=contmatwide[i,2..lastcol]
	lev1vec=select(lev1vec, lev1vec:!=.)
	size1=cols(lev1vec)
	//end
	if(size1>0) {
	//mata
		SP=gcount+1
		EP=gcount+size1
		// Notice: write the level of distance in the third col
		newmat[SP..EP,.]=J(size1,1,i),lev1vec',J(size1,1,1)
		gcount=gcount+size1
		//end
		// Loop over the elements of the distance 1 LSOAs
		for(j=1;j<=size1;j++) {
		//mata
			curid=lev1vec[1,j]
			lev2vec=contmatwide[curid,2..lastcol]
			lev2vec=select(lev2vec, lev2vec:!=.)
			size2=cols(lev2vec)
			SP=gcount+1
			EP=gcount+size2
			newmat[SP..EP,.]=J(size2,1,i),lev2vec',J(size2,1,2)
			gcount=gcount+size2
			//end
		}
	}
	else {
		SP=gcount+1
		EP=gcount+1
		newmat[SP..EP,.]=J(1,1,i),.,J(1,1,1)
		gcount=gcount+1
	}
}

distmat=newmat[1..gcount,.]
end

clear
mata 
st_addobs(rows(distmat))
st_addvar("long","id1")
st_store(.,"id1",distmat[.,1])
st_addvar("long","id2")
st_store(.,"id2",distmat[.,2])
st_addvar("int","level")
st_store(.,"level",distmat[.,3])
end

drop if id1==id2
* Drop the islands
drop if id2==.
* Keep the lowest level to avoid the coming back
* from neighboring LSOAs
sort id1 id2 level
bysort id1 id2: keep if _n==1

* Then, remove the double countings
* like 1-2 and 2-1
* To do that, it is sufficient to keep the couples
* where the id1 is smaller than id2
keep if id1<id2

save Gis\LSOA\DistanceLongMatrixLev2.dta, replace

****************************
* 4. Export PostCodes to convert in WGS84 (to be used for 
* home-distance calculations)
use LookupTables\ONSPD_FEB_2012_UK_O.dta, clear
keep PCDS OSEAST100M OSNRTH100M
outsheet using LookupTables\ONSPD_FEB_2012_UK_OForGis.csv, delimiter(;) replace
* (some work on GIS, that produced ONSPD_FEB_2012_UK_OBNG.shp and 
* ONSPD_FEB_2012_UK_OWGS84.shp)
use LookupTables\ONSPD_FEB_2012_UK_O_WGS84.dta, clear
rename pcds PCD3
merge 1:1 PCD3 using LocalExchanges\PostCodesLEsUnique.dta
keep if _merge==3
drop _merge
drop OSEAST100M OSNRTH100M
rename code le_code
merge m:1 le_code using Gis\LEs\DPaddressBookEng2WGS84ForMerge.dta
keep if _merge==3
drop _merge
vincenty x_coord y_coord le_x le_y, v(distance) inkm
drop if distance>15
bysort le_code: egen home_dist=mean(distance)
bysort le_code: keep if _n==1
keep le_code home_dist
rename le_code code
save Gis\LEs\Home_distance.dta, replace

** End geo-spatial import
*****************************************************************

*****************************************************************
* PART 3. Data merge and identification of the contiguous LSOAs

use LookupTables\ONSPD_FEB_2012_UK_O.dta, clear
rename PCDS PCD3
keep PCD PCD2 PCD3 OSCTY OSLAUA CTRY PCT LEA OSHLTHAU OLDHA OACODE SOA1 SOA2 OAC
merge 1:1 PCD3 using LocalExchanges\PostCodesLEsUnique.dta
keep if _merge==3
drop _merge

bysort code: gen postLE=_N
bysort SOA1: gen postLA=_N
bysort SOA1 code: gen postLALE=_N
gen sh_le=postLALE/postLA

bysort SOA1: keep if _n==1
keep if sh_le==1

keep SOA1 code
rename SOA1 lsoa_code
rename code le_code
merge 1:1 lsoa_code using Demog\LSOADemogs.dta   // Add demographics
drop if _merge==2
drop _merge

gen state=substr(lsoa_code,1,1)
drop if state=="W"  // No Wales in the health data
drop state

* Merge with Geo data
merge 1:1 lsoa_code using Gis\LSOA\LSOA_2011_WGS84ForMerge.dta
keep if _merge==3
drop _merge
merge m:1 le_code using Gis\LEs\DPaddressBookEng2WGS84ForMerge.dta
keep if _merge==3
drop _merge

* Compute distance LSOA-LE
vincenty x_lsoa y_lsoa le_x le_y, v(distance) inkm
preserve
keep lsoa_code le_code x_lsoa y_lsoa le_x le_y distance id
save Gis\LSOA\DistancesLSOAsLEs.dta, replace
restore

* Use the distance matrix between LSOAs
use Gis\LSOA\DistanceLongMatrixLev2.dta, clear
rename id1 id
merge m:1 id using Gis\LSOA\DistancesLSOAsLEs.dta
/* The _merge==2 (2 LSOAs) are probably an error of the contiguity matrix
routine that does not recognize this polygons
The _merge==1 are LSOAs that cannot be used because their share is not 1
*/
keep if _merge==3
drop _merge
foreach variabile in  lsoa_code le_code x_lsoa y_lsoa le_x le_y distance {
	rename `variabile' `variabile'_1
}
* Merge contiguous LSOAs
rename id id_1
rename id2 id
merge m:1 id using Gis\LSOA\DistancesLSOAsLEs.dta
keep if _merge==3
drop _merge
foreach variabile in  lsoa_code le_code x_lsoa y_lsoa le_x le_y distance {
	rename `variabile' `variabile'_2
}
rename id id_2
gen contig_diLE=(le_code_1!=le_code_2)
gen diffdist=abs(distance_1-distance_2)

*********************************************************************
* Perform the distance selection
* First check the balance without looking at distance
global subsample0 " "
global subsample1 "keep if contig_diLE==1"
global subsample2 "keep if level==1"

preserve
gen tempid=_n
* Two criteria: different LEs and sharing boarder
$subsample1 
$subsample2
reshape long id_ $demoglist, i(tempid ) j(ordine)
foreach demog in $demoglist {
	di "  "
	di "Demographic: `demog':"
	ttest `demog', by(ordine)
}
restore

* Create treated and controls. Treated are those closer
* to the LE 
gen treat1=distance_1<distance_2
$subsample1
$subsample2
gen newid=_n
order newid, first
preserve
keep if treat1==1  // This guys don't have to be switched
save TempData\TempForSwitch1.dta, replace
save TempData\TempForSwitch1.dta, v(11) replace
restore
preserve
keep if treat1==0  // This guys have to be switched
foreach vari in id_ lsoa_code_ le_code_ x_lsoa_ y_lsoa_ le_x_ le_y_ distance_ $demoglist {
	rename `vari'1 `vari'0
	rename `vari'2 `vari'1
	rename `vari'0 `vari'2
}
save TempData\TempForSwitch2.dta, replace
restore

use TempData\TempForSwitch1.dta, clear
append using TempData\TempForSwitch2.dta
sort newid

gen check=distance_2<distance_1
table check
// OK, all zeros now
drop check

keep newid id_1 id_2 level lsoa_code_1 le_code_1 distance_1 lsoa_code_2 le_code_2 distance_2 contig_diLE
save TempData\MatchedLSOAs.dta, replace

* I extract contiguous LSOAs
gsort lsoa_code_1 -distance_2
by lsoa_code_1 : keep if _n==1
gen ddist=distance_2 -distance_1
sum ddist
gsort lsoa_code_2 -ddist
by lsoa_code_2 : keep if _n==1
sort lsoa_code_1 lsoa_code_2
* Put on a matrix the list of the treated to be sure they are not in the control
mkmat id_1, matrix(list_id1)
count
global nobs=r(N)
scalar idv=list_id1[1,1]
gen temp=id_2==idv
gen dropif=0
forval i=1/$nobs {
	scalar idv=list_id1[`i',1]
	replace temp=id_2==idv
	replace dropif=dropif+temp
}
drop if dropif==1
save TempData\MatchedLSOAsStrict.dta, replace


*****************************************************************
* PART 4. Match of selected LSOAs with the health data

* 1. The dataset on matched LSOAs is in wide, with _1 and _2 to identify 
* the matched LSOAs, produce list to be matched later
use TempData\MatchedLSOAsStrict.dta, clear
keep lsoa_code_1
bysort lsoa_code_1: keep if _n==1
rename lsoa_code_1 soal
save TempData\MatchedLSOAsListID1.dta, replace
use TempData\MatchedLSOAsStrict.dta, clear
keep lsoa_code_2
bysort lsoa_code_2: keep if _n==1
rename lsoa_code_2 soal
save TempData\MatchedLSOAsListID2.dta, replace
	
forval Y=2000/2012 {
	use TempData\MatchedLSOAsListID1.dta, clear
	merge 1:m soal using "Discharges\DatasetDeliveries_`Y'.dta"
	keep if _merge==3
	drop _merge
	rename soal lsoa_code_1
	save TempData\MatchedLSOAsListID1_`Y'.dta, replace

	use TempData\MatchedLSOAsListID2.dta, clear
	merge 1:m soal using "Discharges\DatasetDeliveries_`Y'.dta"
	keep if _merge==3
	drop _merge
	rename soal lsoa_code_2
	save TempData\MatchedLSOAsListID2_`Y'.dta, replace
}

********************************************************************************
* 2. Go for a long version of the data, so prepare two blocks to be appended
forval Y=2000/2012 {
	use TempData\MatchedLSOAsStrict.dta, clear
	keep if level==1
	bysort id_1: keep if _n==1
	bysort id_2: keep if _n==1
	sort id_1

	merge 1:m lsoa_code_1 using TempData\MatchedLSOAsListID1_`Y'.dta
	keep if _merge==3
	drop _merge
	drop id_2 lsoa_code_2 le_code_2 distance_2
	rename id_1 id
	rename lsoa_code_1 lsoa_code
	rename le_code_1 le_code
	rename distance_1 distance
	gen treated=1
	save TempData\DeliveriesLSOAs1_`Y'.dta, replace

	use TempData\MatchedLSOAsStrict.dta, clear
	keep if level==1
	bysort id_1: keep if _n==1
	bysort id_2: keep if _n==1
	sort id_1

	merge 1:m lsoa_code_2 using TempData\MatchedLSOAsListID2_`Y'.dta
	keep if _merge==3
	drop _merge
	drop id_1 lsoa_code_1 le_code_1 distance_1
	rename id_2 id
	rename lsoa_code_2 lsoa_code
	rename le_code_2 le_code
	rename distance_2 distance
	gen treated=0
	save TempData\DeliveriesLSOAs2_`Y'.dta, replace
}

* Append all years:
* Here: Do we need all these years now??????
use TempData\DeliveriesLSOAs1_2000.dta, clear
append using TempData\DeliveriesLSOAs2_2000.dta
forval Y=2001/2012 {
	append using TempData\DeliveriesLSOAs1_`Y'.dta, force
	append using TempData\DeliveriesLSOAs2_`Y'.dta, force
}

egen procode_id=group(procode)

save FinalData\DelivMatchedLSOAsAllYears.dta, replace

*************************************************
* Generate more variables

* Time variables

gen hesmonth=month_adm
gen hesqrt=1 if hesmonth>=4 & hesmonth<=6
replace hesqrt=2 if hesmonth>=7 & hesmonth<=9
replace hesqrt=3 if hesmonth>=10 & hesmonth<=12
replace hesqrt=4 if hesmonth>=1 & hesmonth<=3

egen period=group(hesyear hesqrt)

gen hessmt=hesqrt<=2
replace hessmt=2 if hesqrt>2
egen periodh=group(hesyear hessmt)

sort newid id
order treated, after(id)
drop if hesyear==2012
keep if hesyear>=2000
keep if epiorder==1

gen qtr_adm=quarter(admidate)
la var qtr_adm "Quarter of hospital admission"

gen yearqr=(year_adm*10)+qtr_adm 

gen d2006=hesyear>=2006 
la var d2006 "Post period"

gen did=treated*d2006
la var did "Did"

gen distdid=ddist*did*1.07

qui tab hesyear, gen(dyear)
qui tab year_adm, gen(dyear_adm)

forval anno=1997/2012 {
	gen treat_`anno'=treated*hesyear==`anno' 
}

la var treated "Treated"
la var hesyear "Year"

**************************************
* Patient's variables 

la var agegroup "Age group"
la var ccmorb "Compl \& Co-morbidities" 
la var cervix "Cervix"
la var cordprol "Cord"
la var disprop "Disproportion"
la var hypereclamp "Hypertens. eclampsia"
la var prematmem "Premature rupture memb"
la var prolongpg "Prolonged pregnancy"
la var renal "Renal failure"
la var twins "Twins"

gen vaginstr=(del_meth==3 | del_meth==4 | del_meth==5 | del_meth==6 | del_meth==7)
la var vaginstr "Vag del with instrument"

gen vagnoinstr=(del_meth==8 | del_meth==9)
la var vagnoinstr "Vag del without instrument"

gen trvag=(trvaginstr==1 | trvagnoinstr==1)
la var trvag "Trauma vag del"

replace patage=. if patage>70 | patage<13
* var matage is incomplete. Use "patage" instead.

la var agedum2 "Age 20-24"
la var agedum3 "Age 25-29"
la var agedum4 "Age 30-34"
la var agedum5 "Age 35-39"
la var agedum6 "Age 40+"
 
la var imd04ed "Index education"
la var imd04i "Index income"
la var imd04rk "Index Multiple Deprivation" //Overall rank
la var twins "Twins"

gen white=(ethnos=="A" | ethnos=="B" | ethnos=="C" | ethnos=="0")
la var white "White"

gen black=(ethnos=="M" | ethnos=="N" | ethnos=="P" | ethnos=="1"| ethnos=="2" | ethnos=="3")
la var black "Black"

gen asian=(ethnos=="F" | ethnos=="H" | ethnos=="J" | ethnos=="K"| ethnos=="L" | ethnos=="4"| ethnos=="5" | ethnos=="6"| ethnos=="7")
la var asian "Asian"

gen lbw=(birweit_1<2500)
replace lbw=. if birweit_1==9999
la var lbw "Low Birth Weight (<2500)"

gen gestage=gestat_1
replace gestage=. if gestat_1==99  
la var gestage "Gestational Age (weeks)"

gen preemie=(gestage<=36)
replace preemie=. if gestage==. 
la var preemie "Premature baby"

gen dischar=(dismeth==1 | dismeth==2 | dismeth==3 )
replace dischar=. if dismeth==9
la var dischar "Discharged"

replace csec=csec*100
replace del_csecelect=del_csecelect*100
replace del_csecemerg=del_csecemerg*100

g stillbirth=(birstat_1==2 | birstat_1==2 | birstat_1==4)
replace stillbirth=. if birstat_1==9
la var stillbirth "Still birth"

g resus=(biresus_1==3 | biresus_1==4 | biresus_1==5 | biresus_1==6)
replace resus=. if biresus_1==8 | biresus_1==9
la var resus "Resuscitation"


* Some are still both in the treated and in the control group 
bysort id: egen avgtreat=mean(treated)
*table avgtreat
drop if avgtreat==0.5

gen anesth=100 if delprean<=7
replace anesth=0 if delprean==8
la var anesth "Anaesthetic during labor"


************** Merge with hospital location data
rename procode procode5
rename procode3 procode

merge m:1 procode using $data2/hospital_locations.dta
drop if _merge==2

* There are 2 procode that are not matched. But they are listed in "nhs-non-nhs-ods-codes.xls"
* and in "HList3.csv"
replace oseast1m=546346 if procode=="RYQ" & oseast1m==.
replace osnrth1m=170945 if procode=="RYQ" & osnrth1m==.
replace oseast1m=515323 if procode=="RYR" & oseast1m==.
replace osnrth1m=103187 if procode=="RYR" & osnrth1m==.

************************
drop _merge
merge m:1 lsoa_code using "Gis\LSOA\LSOAsCentroidsForMerge.dta"
// All matched
drop if _merge==2
drop _merge

* Given the small distances, we simply use Pitagora
gen dist_hosp=sqrt((LSOAxcoord-oseast1m)^2 +(LSOAycoord-osnrth1m)^2)
replace dist_hosp=dist_hosp/1000

la var dist_hosp "Distance"


********************************************************************************
** Final work on the variables
* Generate some variables
gen elec=del_csecelec
la var elec "Elective C-sec"

gen emerg=del_csecemerg
la var emerg "Emergency C-sec"

egen hospnr=group(procode) // We need it for hospitals' FEs


gen prevpreg=0 if numpreg==0
replace prevpreg=1 if numpreg>0 & numpreg!=99
foreach lname in Z340 Z355 Z356{
		replace prevpreg = 0 if prevpreg==. & (diag3_01 == "`lname'" | diag4_01 == "`lname'")		
		replace prevpreg = 0 if prevpreg==. & (diag_1 == "`lname'" | diag_2 == "`lname'" | diag_3 == "`lname'" | diag_4 == "`lname'" | diag_5 == "`lname'" | diag_6 == "`lname'" | diag_7 == "`lname'" | diag_8 == "`lname'" | diag_9 == "`lname'" | diag_10 == "`lname'")
}
replace prevpreg=1 if vbac==1 & prevpreg==.
replace prevpreg=1 if previousCS==1 & prevpreg==.

gen experienced=prevpreg
la var experienced "Multiple-time"

gen expdid=experienced*did
la var expdid "Multiple $\times$ Did"

gen expd2006=experienced*d2006

replace previousCS=0 if experienced==0

* Income deprivation (mean/median-split) - see part on heterogeneities
sum imd04i, d
gen high_inc = (imd04i < r(mean))
la var high_inc "High Income"

gen highinc_did=high_inc*did
la var highinc_did "High Inc $\times$ Did"

gen highinc2006=high_inc*2006

sum imd04i, d
gen high_incmed = (imd04i < r(p50))
la var high_incmed "High Income-median"

gen highincmed_did=high_incmed*did
la var highincmed_did "High Inc $\times$ Did"

gen highincmed2006=high_incmed*2006

* Education deprivation (mean/median-split) - see part on heterogeneities
sum imd04ed, d
gen high_educ = (imd04ed < r(mean))
la var high_educ "High Education"

gen higheduc_did=high_educ*did
la var higheduc_did "High Educ $\times$ Did"

gen higheduc2006=high_educ*2006

sum imd04ed, d
gen high_educmed = (imd04ed < r(p50))
la var high_educmed "High Educ-median"

gen higheducmed_did=high_educmed*did
la var higheducmed_did "High Educ $\times$ Did"

gen highinceduc2006=high_educmed*2006

replace previousCS=0 if experienced==0

* Generate the fixed effects
qui tab newid, gen(newid_)
forval i=1/1209 {
	gen newid_`i'_trend=newid_`i'*hesyear
}

save FinalData\delivery_main.dta, replace


********************************************************************************
** Dataset for the speed regression (merge with broadband info)

use FinalData\delivery_main.dta, clear

sort hesyear period

rename le_code LE
merge m:1 LE using $extradatapath/BBdevelopment/ActivationPeriodsFull.dta
keep if _merge==3
drop _merge

rename LE le_code
merge m:1 le_code using $extradatapath/BBdevelopment/le_codelist.dta
keep if _merge==3
drop _merge

merge m:1 le_code hesyear hesqrt using $extradatapath/BBdevelopment/BBModelPredForMerge.dta
drop if _merge==2 // all matched!
drop _merge


gen adsl_tier=0
replace adsl_tier=1 if hesyear>=ADSL_active_year
replace adsl_tier=2 if hesyear>=llu_year
replace adsl_tier=3 if hesyear>=ADSL2plus_year

* Use the coefficients in Table 1, pag. 18 of Ahlfeldt, Koutroumpis and Valletti
gen speed=7.869-0.293*distance^2+0.058*distance^3-0.003*distance^4+lecoefT1 if adsl_tier==1
replace speed=8.214-0.287*distance^2+0.07*distance^3-0.005*distance^4+lecoefT1 if adsl_tier==2
replace speed=8.672-0.491*distance^2+0.141*distance^3-0.011*distance^4+lecoefT1 if adsl_tier==3

replace speed=exp(speed)
replace speed=128 if adsl_tier==0 | speed<128
replace speed=speed/1000

save FinalData\FinalDeliveryForSpeedRegressions.dta, replace


***** END OF DATA CONSTRUCTION +++++++++++++++++++++++++++++++++++++++++++++++++
